from flask import Flask, request, jsonify
import random
import platform
from Config.Setting import *
from Database.RedisClient import Redis_cliient

app = Flask(__name__)
@app.route("/",methods=["GET"])
def index():
    api_desc = {
        "desc":"首次使用请查阅后使用，代理ip分为认证和非认证，请根据type类型进行查看，以下是API的接口",
        "api":{
            "get": "随机获取一个代理ip，也可以指定获取数量，参数：num 不得超过100，返回数量默认为1",
            "all": "获取所有代理ip，为了降低数据消耗，讲限制最大返回数为1000，并且返回数据库存储数量！",
            "del": "删除指定的某个ip，调度任务也会定时进行检查并且删除key ，参数proxy_str",
        }
    }
    return jsonify(api_desc)

@app.route("/get/", methods=["GET"])
def get():
    success = {
        "code":"1",
        "message":"获取成功",
        "total":"",
        "proxy_list":[]
    }
    token = request.args.get('token', None)
    if token != SERVER_API["token"]:
        return jsonify({"code":"-1","message":"token 不得为空"})
    num = request.args.get('num',"1")
    if not str(num).isdigit():
        num = 1
    else:
        if int(num)>=100 or int(num) <=0:
            num = 1
        num = int(num)
    success.update({"total":num})
    proxy_list = Redis_cliient.getAll()
    if not proxy_list:
        success.update({"message":"库中没有可用代理！","code":"-1"})
    else:
        success.update({"proxy_list":random.sample(proxy_list, num)})
    return jsonify(success)

@app.route("/all/", methods=["GET"])
def all():
    success = {
        "code": "1",
        "message": "获取成功",
        "total": "",
        "proxy_list": []
    }
    token = request.args.get('token', None)
    if token != SERVER_API["token"]:
        return jsonify({"code": "-1", "message": "token 不得为空"})
    proxy_list = Redis_cliient.getAll()[:1000]
    if not proxy_list:
        success.update({"message": "库中没有可用代理！", "code": "-1"})
    else:
        success.update({"proxy_list": proxy_list,"total":len(proxy_list)})
    return jsonify(success)

@app.route("/del/", methods=["GET"])
def delete():
    success = {
        "code": "1",
        "message": "删除成功！",
    }
    token = request.args.get('token', None)
    if token != SERVER_API["token"]:
        return jsonify({"code": "-1", "message": "token 不得为空"})
    proxy_str = request.args.get('proxy_str', None)
    if not proxy_str:
        success.update({"code":"-1","message":"需要删除的代理ip不能为空"})
        return jsonify(success)
    del_res = Redis_cliient.delete("proxy_str")
    if del_res == 1:
        return jsonify(success)
    success.update({"code":"-1","message":"代理删除失败！"})

if platform.system() != "Windows":
    import gunicorn.app.base
    from six import iteritems


    class StandaloneApplication(gunicorn.app.base.BaseApplication):

        def __init__(self, app, options=None):
            self.options = options or {}
            self.application = app
            super(StandaloneApplication, self).__init__()

        def load_config(self):
            _config = dict([(key, value) for key, value in iteritems(self.options)
                            if key in self.cfg.settings and value is not None])
            for key, value in iteritems(_config):
                self.cfg.set(key.lower(), value)

        def load(self):
            return self.application

def runFlask():
    app.run(host=SERVER_API["HOST"], port=SERVER_API["PORT"])


def runFlaskWithGunicorn():
    _options = {
        'bind': '%s:%s' % (DB_HOST, DB_PORT),
        'workers': 4,
        'accesslog': '-',  # log to stdout
        'access_log_format': '%(h)s %(l)s %(t)s "%(r)s" %(s)s "%(a)s"'
    }
    StandaloneApplication(app, _options).run()

if __name__ == '__main__':
    if platform.system() == "Windows":
        runFlask()
    else:
        runFlaskWithGunicorn()

